package com.imoblife.brainwavestus.obpurchaseSystem;


import java.util.ArrayList;

import junit.framework.Assert;

import com.imoblife.brainwavestus.R;
import com.imoblife.brainwavestus.obpurchaseSystem.OBpurchaseSystem.OBPurchaseNotifier;
import com.imoblife.brainwavestus.tapjoy.TJCVirtualGoodsConnection;
import com.imoblife.brainwavestus.tapjoy.TJCVirtualGoodsData;
import com.imoblife.brainwavestus.tapjoy.TapjoyConnect;
import com.imoblife.brainwavestus.tapjoy.TapjoyConnectCore;
import com.imoblife.brainwavestus.tapjoy.TapjoyConstants;
import com.imoblife.brainwavestus.tapjoy.TapjoyLog;
import com.imoblife.brainwavestus.tapjoy.VGStoreItem;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Debug;
import android.os.Handler;
import android.util.Log;

public class BaseOnTJpurchaseSystem {

	private static String TAG = "BaseOnTJpurchaseSystem";

	private TJCVirtualGoodsConnection OBpurchaseSystem = null;

	private Context mContext;
	private OBPurchaseNotifier obnotifierpuchase; // ��������
	public AlertDialog exceptionDialog; // ���?���쳣�Ĵ���
	private AlertDialog getMoreItemDialog;
	private ProgressDialog progressDialog;
	private TJCVirtualGoodsConnection tapjoyVGConnection = null;
	private PurchaseVirtualGoodTask purchaseVirtualGoodTask = null;
	TJCVirtualGoodsData tjcVirtualGoodsData;

	public BaseOnTJpurchaseSystem(Context context) {

		mContext = context;

		tapjoyVGConnection = new TJCVirtualGoodsConnection(
				TapjoyConstants.TJC_SERVICE_URL,
				TapjoyConnectCore.getURLParams());

		tjcVirtualGoodsData = new TJCVirtualGoodsData(context,
				context.getPackageName());
	}

	protected BaseOnTJpurchaseSystem(Service service) {
		mContext = service;
		tapjoyVGConnection = new TJCVirtualGoodsConnection(
				TapjoyConstants.TJC_SERVICE_URL,
				TapjoyConnectCore.getURLParams());
	}

	private class PurchaseVirtualGoodTask extends
			AsyncTask<VGStoreItem, Void, VGStoreItem> {

		private static final String TAPJOY_VIRTUAL_GOODS = "PurchaseVirtualGoodTask";
		String responseMessage = null;
		boolean networkTimeout = false;
		boolean successfulPurchase = false;

		protected VGStoreItem doInBackground(VGStoreItem... storeItem) {

			try {
				Log.d(TAG,
						"virtual_good_id: " + storeItem[0].getVgStoreItemID());

				String response = tapjoyVGConnection
						.purchaseVGFromServer(storeItem[0].getVgStoreItemID());
				Log.d(TAG, "response=" + response);

				if (response != null && response.length() > 0) {
					ArrayList<String> resultList = TJCVirtualGoodsData
							.parsePurchaseVGWithCurrencyResponse(response,
									mContext);

					if (resultList != null && resultList.size() > 0) {

						if (!((String) resultList.get(2)).equals("")) {
							networkTimeout = true;
						}

						responseMessage = (String) resultList.get(0);

						if (resultList.get(1).equals("false")) {
							successfulPurchase = false;
						} else {
							successfulPurchase = true;
						}

					} else {
						networkTimeout = true;
					}

					TapjoyLog.i(TAPJOY_VIRTUAL_GOODS, "responseMessage: "
							+ responseMessage + ", successfulPurchase: "
							+ successfulPurchase);

					return storeItem[0];
				} else {
					networkTimeout = true;
				}

				return storeItem[0];
			} catch (Exception e) {
				TapjoyLog.e(TAPJOY_VIRTUAL_GOODS,
						"Failed to purchase item.  e: " + e.toString());
				networkTimeout = true;
			}
			return storeItem[0];
		}

		private void showExceptionDialog() {

			exceptionDialog = new AlertDialog.Builder(mContext)
					.setMessage(R.string.network_down_message)
					.setNegativeButton(R.string.cancel,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									dialog.cancel();
								}
							})
					.setPositiveButton(R.string.retry,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									dialog.cancel();
									purchaseVirtualGood();
								}

							}).show();

		}

		private void showGetMoreItemDialog() {

			int message = -1;

			if (responseMessage.equalsIgnoreCase("Balance too low")) {
				responseMessage = "You do not have enough balance to purchase this item.";
				message = R.string.balance_too_low;
			} else {
				message = R.string.alreadypurcused;
				if (obnotifierpuchase != null) {
					obnotifierpuchase.noticeSuccess(vgStoreItem
							.getVgStoreItemID());
				}
			}

			// Dialog Box when balance is too low.
			getMoreItemDialog = new AlertDialog.Builder(mContext)
					.setTitle("")
					.setMessage(message)
					.setPositiveButton(R.string.ok,
							new DialogInterface.OnClickListener() {
								// OKAY
								public void onClick(DialogInterface dialog,
										int whichButton) {
									getMoreItemDialog.cancel();
								}
							})
					.setNegativeButton(R.string.get_more,
							new DialogInterface.OnClickListener() {
								// GET MORE
								public void onClick(DialogInterface dialog,
										int whichButton) {
									showOffers();
								}
							}).show();
		}

		protected void onPostExecute(final VGStoreItem storeItem) {

			progressDialog.cancel();

			if (networkTimeout) {
				// ���������쳣
				showExceptionDialog();

			} else {

				if (successfulPurchase == false) {// ERROR trying to download.
					showGetMoreItemDialog();
				} else { // Successful purchase.
					if (obnotifierpuchase != null) {
						obnotifierpuchase.noticeSuccess(storeItem
								.getVgStoreItemID());
					}
				}
				return;
			}

			// If we got an exception, then don't try to fetch the store items.
			if (!networkTimeout) {
				TapjoyLog.i(TAPJOY_VIRTUAL_GOODS,
						"Now fetch store items again...");
			}

			// TapjoyLog.i(TAPJOY_VIRTUAL_GOODS, "Done!");
		}
	}

	private void showOffers() {
		TapjoyConnect.getTapjoyConnectInstance().showOffers();
	}

	private VGStoreItem vgStoreItem;

	public void purchaseVirtualGood(OBPurchaseNotifier notifierPurchase,
			final String tapjoyId) {
		
		this.obnotifierpuchase = notifierPurchase;
		vgStoreItem = new VGStoreItem();
		vgStoreItem.setVgStoreItemID(tapjoyId);
		purchaseVirtualGood();
	}

	private void purchaseVirtualGood() {
		progressDialog = ProgressDialog.show(mContext, "",
				mContext.getString(R.string.processing_message), true);
		purchaseVirtualGoodTask = new PurchaseVirtualGoodTask();
		purchaseVirtualGoodTask.execute(vgStoreItem);

	}

	public ArrayList<VGStoreItem> getAllPurchasedItemsFromServer() {

		// return TapjoyConnect.getTapjoyConnectInstance().getPurchasedItems();
		try {
			String response = tapjoyVGConnection
					.getAllPurchasedItemsFromServer(0, 200);
			
			if (response != null && response.length() > 0) {
				return TJCVirtualGoodsData.parseVGItemListResponse(response,
						VGStoreItem.PURCHASED_ITEM, mContext);
			}
		} catch (Exception e) {

		}

		return null;

	}

	public void printFromServerGetAllVirtualGoods() {

		new Thread() {

			public void run() {
				try {
					String response = tapjoyVGConnection
							.getAllStoreItemsFromServer(0, 200);
					
					if (response != null && response.length() > 0) {
						ArrayList<VGStoreItem> storeItems = TJCVirtualGoodsData
								.parseVGItemListResponse(response,
										VGStoreItem.STORE_ITEM, mContext);
						for (VGStoreItem vgStoreItem : storeItems) {

							Log.d("ServerGetAll", vgStoreItem.getName()
									.toLowerCase().replaceAll(" ", "_")
									+ " " + vgStoreItem.getVgStoreItemID());

						}

					}
				} catch (Exception e) {

				}

			}
		}.start();

	}
}
